import axios from "axios";

export const getAddress = async (latitude, longitude) => {
    try {
        const apiKey = '0a029712401901279e1a966303df2f7e';
        const location = `${longitude},${latitude}`;
        const url = `https://restapi.amap.com/v3/geocode/regeo?key=${apiKey}&location=${location}&extensions=all&output=JSON`;

        const response = await axios.get(url);

        console.log("高德地图 API 返回的完整数据:", response.data); // 打印完整数据

        if (response.data.status === '1') {
            const regeocode = response.data.regeocode;
            let formattedAddress = regeocode.formatted_address;

            if (!formattedAddress && regeocode.addressComponent) {
                const ac = regeocode.addressComponent;
                formattedAddress = `${ac.province || ''}${ac.city || ''}${ac.district || ''}${ac.streetNumber?.street || ''}${ac.streetNumber?.number || ''}`; // 使用可选链操作符
            }

            return formattedAddress || '地址解析失败';
        } else {
            console.error('获取地址信息失败：' + response.data.info);
            return '获取地址信息失败：' + response.data.info; // Include the error info
        }
    } catch (error) {
        console.error('获取地址信息失败：' + error.message);
        return '获取地址信息失败：' + error.message;
    }
};